<template>
  <!-- 预算收支情况折线图 -->
  <div class="budgetChartPage">
    <div class="btnGroupBox">
      <div class="bigBtnBox" v-if="btnShowFlag">
        <div
          class="inflowBtn m-r10"
          :class="bigBtnActiveFlag ? 'btnActive' : ''"
          @click="showInflowData">
          流入
        </div>
        <div
          class="outflowBtn"
          :class="bigBtnActiveFlag ? '' : 'btnActive'"
          @click="showOutflowData">
          流出
        </div>
      </div>
      <div class="smBtnBox" v-if="!btnShowFlag">
        <div
          class="smBtnItemStyle"
          :class="smBtn1ActiveFlag ? 'btnSmActive' : ''"
          @click="btnTypeChange(1)">
          收入
        </div>
        <div
          class="smBtnItemStyle"
          :class="smBtn2ActiveFlag ? 'btnSmActive' : ''"
          @click="btnTypeChange(2)">
          成本
        </div>
        <div
          class="smBtnItemStyle"
          :class="smBtn3ActiveFlag ? 'btnSmActive' : ''"
          @click="btnTypeChange(3)">
          利润
        </div>
      </div>
    </div>
    <div class="chartBox" id="budgetChart"></div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import echarts from "@/common/utils/echarts.js";
import { changeNumToWan } from "../../utils/handelScreen";
import { budgetApi } from "@/api-dashboard/leaderApi";

// 按钮点击切换状态
const btnShowFlag = ref(true);
const bigBtnActiveFlag = ref(true);
const smBtn1ActiveFlag = ref(true);
const smBtn2ActiveFlag = ref(false);
const smBtn3ActiveFlag = ref(false);
const getYearVal = ref(null);

// 流入流出按钮状态切换
const showInflowData = () => {
  if (!bigBtnActiveFlag.value) bigBtnActiveFlag.value = !bigBtnActiveFlag.value;
  getFundData(0, getYearVal.value);
  getFundAchievment(0, getYearVal.value)
};
const showOutflowData = () => {
  if (bigBtnActiveFlag.value) bigBtnActiveFlag.value = !bigBtnActiveFlag.value;
  getFundData(1, getYearVal.value);
  getFundAchievment(1, getYearVal.value)
};
// 小按钮状态切换
const btnTypeChange = (type) => {
  if (type === 1 && !smBtn1ActiveFlag.value) {
    // 收入
    smBtn1ActiveFlag.value = true;
    smBtn2ActiveFlag.value = false;
    smBtn3ActiveFlag.value = false;
  }
  if (type === 2 && !smBtn2ActiveFlag.value) {
    // 成本
    smBtn2ActiveFlag.value = true;
    smBtn1ActiveFlag.value = false;
    smBtn3ActiveFlag.value = false;
  }
  if (type === 3 && !smBtn3ActiveFlag.value) {
    // 利润
    smBtn3ActiveFlag.value = true;
    smBtn1ActiveFlag.value = false;
    smBtn2ActiveFlag.value = false;
  }
  getManageData(type - 1, getYearVal.value);
  getMngAchievment(type - 1, getYearVal.value)
};

// 折线点的标记图
const piontMarkImgUrl = require("@/assets/screenImg/leaderImg/pointLine.png");
// 图表数据
const budgetChartRef = ref(null);
const options = reactive({
  color: ["#80FFA5", "#00C6FF"],
  tooltip: {
    trigger: "item",
    appendToBody: true,
    className: "screenChartToolTipBox",
    textStyle: {
      color: '#fff',
      fontSize: 10,
    },
    borderWidth: 0,
    borderColor: "none",
    backgroundColor: "none",
    formatter: function (params) {
      let htmlStr = "<div>";
      htmlStr += "<div class='tip-head'>年度达成率</div>";
      htmlStr += "<div class='tip-cn'>";
      htmlStr += "<div class='cn-item'>";
      if (btnShowFlag.value) {
        htmlStr += "<span class='item-title'>资金预算：</span>";
        htmlStr += "<span class='item-cn'>";
        htmlStr += `${fundAchievmentRate.value}`;
        htmlStr += "%</span>";
      } else {
        htmlStr += "<span class='item-title'>经营预算：</span>";
        htmlStr += "<span class='item-cn'>";
        htmlStr += `${manageAchievmentRate.value}`;
        htmlStr += "%</span>";
      }
      htmlStr += "</div>";
      htmlStr += "</div>";
      htmlStr += "</div>";
      return htmlStr;
    },
  },
  legend: {
    top: "3",
    left: "100",
    data: ["实际", "预算"],
    textStyle: {
      color: "#D3E3FF",
      fontWeight: "500",
      fontFamily: "SourceHanSansMedium",
    },
    itemStyle: {
      opacity: 0,
    },
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "28%",
    containLabel: true,
  },
  xAxis: [
    {
      type: "category",
      name: "单位(月)",
      nameTextStyle: {
        color: "#D3E3FF",
        fontWeight: "500",
        align: "right",
        verticalAlign: "bottom",
        lineHeight: -60,
      },
      boundaryGap: false,
      data: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
      axisLabel: {
        color: "#D3E3FF",
      },
      axisTick: {
        // 去掉X轴刻度
        show: false,
      },
      axisLine: {
        // 不显示X轴线
        show: false,
      },
    },
  ],
  yAxis: [
    {
      type: "value",
      name: "单位(万元)",
      nameTextStyle: {
        color: "#D3E3FF",
        fontWeight: "500",
        align: "right",
        padding: [0, -10, 0, 0]
      },
      // 横向分割线配置
      splitLine: {
        lineStyle: {
          type: [5, 10], // 虚线
          color: ["#B0D7FF"],
          opacity: 0.3,
        },
      },
      axisLabel: {
        color: "#D3E3FF",
      },
    },
  ],
  series: [
    {
      name: "实际",
      type: "line",
      lineStyle: {
        // 设置线条颜色
        width: 3,
        color: "#00C6FF",
      },
      showSymbol: false,
      emphasis: {
        focus: "series",
      },
      data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      markPoint: {
        symbol: `image://${piontMarkImgUrl}`,
        symbolKeepAspect: true,
        symbolSize: [10, 89],
        symbolOffset: [0, 42],
        label: {
          show: false,
          color: "red",
          position: "top",
        },
        itemStyle: {
          // 设置线条上点的颜色
          color: "red",
        },
        data: [],
      },
    },
    {
      name: "预算",
      type: "line",
      lineStyle: {
        type: "dotted",
        // 设置线条颜色
        width: 3,
        color: "#1978E5",
      },
      itemStyle: {
        // 设置线条上点的颜色
        color: "#00C6FF",
      },
      showSymbol: false, // 不在折线上显示数据点
      emphasis: {
        focus: "series",
      },
      data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      markPoint: {
        symbol: "circle",
        symbolKeepAspect: true,
        symbolSize: [5, 5],
        symbolOffset: [0, 0],
        label: {
          show: false,
          color: "yellow",
          position: "top",
        },
        data: [],
      },
    },
  ],
});

// 获取资金预算数据 type:0-流入；type:1-流出
const getFundData = (type, yearVal) => {
  let paramObj = {
    year: yearVal,
    flow_direction: type,
  };
  budgetApi.zjys(paramObj).then((res) => {
    const { httpStatusCode, data } = res;
    if (httpStatusCode == 200 && data.records?.length) {
      let dataArr = data.records;
      let getActualDataArr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
      let getPlanDataArr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
      // 从接口获取的数据,并对数据格式进行转换
      dataArr.map((n, i) => {
        let index = n.month - 1;
        getActualDataArr[index] = n.amount_real ? changeNumToWan(n.amount_real) : 0;
        getPlanDataArr[index] = n.amount_plan ? changeNumToWan(n.amount_plan) : 0;
      });
      // 用于在折线图用图片标记点
      let actualMarkPointData = getActualDataArr.map((m, j) => {
        return { coord: [j, m], value: m };
      });
      let planMarkPointData = getPlanDataArr.map((m, j) => {
        return { coord: [j, m], value: m };
      });
      options.series[0].data = getActualDataArr;
      options.series[0].markPoint.data = actualMarkPointData;
      options.series[1].data = getPlanDataArr;
      options.series[1].markPoint.data = planMarkPointData;
    }
    budgetChartRef.value.setOption(options);
  });
};
// 资金预算年度达成率
const fundAchievmentRate = ref('');
const getFundAchievment = (type, yearVal) => {
  let paramObj = {
    year: yearVal,
    flow_direction: type,
  };
  budgetApi.zjysnddcl(paramObj).then((res) => {
    const { httpStatusCode, data } = res;
    if (httpStatusCode == 200 && data.records?.length) {
      let dataArr = data.records
      fundAchievmentRate.value = dataArr[0].achievement_rate ? _.round(dataArr[0].achievement_rate * 100, 2) : '0.00'
    }
    budgetChartRef.value.setOption(options);
  })
}


// 获取经营预算数据 type:0-收入；type:1-成本；type:2-利润
const getManageData = (type, yearVal) => {
  let paramObj = {
    year: yearVal+"",
    operate: type+"",
  };
  budgetApi.jyys(paramObj).then((res) => {
    const { httpStatusCode, data } = res;
    if (httpStatusCode == 200 && data.records?.length) {
      let dataArr = data.records;
      let getActualDataArr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
      let getPlanDataArr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
      // 从接口获取的数据,并对数据格式进行转换
      dataArr.map((n, i) => {
        let index = n.month - 1;
        getActualDataArr[index] = n.amount_real ? changeNumToWan(n.amount_real) : 0;
        getPlanDataArr[index] = n.amount_plan ? changeNumToWan(n.amount_plan) : 0;
      });
      // 用于在折线图用图片标记点
      let actualMarkPointData = getActualDataArr.map((m, j) => {
        return { coord: [j, m], value: m };
      });
      let planMarkPointData = getPlanDataArr.map((m, j) => {
        return { coord: [j, m], value: m };
      });
      options.series[0].data = getActualDataArr;
      options.series[0].markPoint.data = actualMarkPointData;
      options.series[1].data = getPlanDataArr;
      options.series[1].markPoint.data = planMarkPointData;
    }
    budgetChartRef.value.setOption(options);
  });
};
// 经营预算达成率
const manageAchievmentRate = ref('');
const getMngAchievment = (type, yearVal) => {
  let paramObj = {
    year: yearVal+"",
    flow_direction: type+"",
    operate: type+"",
  };
  budgetApi.jyysnddcl(paramObj).then((res) => {
    const { httpStatusCode, data } = res;
    if (httpStatusCode == 200 && data.records?.length) {
      let dataArr = data.records
      manageAchievmentRate.value = dataArr[0].achievement_rate ? _.round(dataArr[0].achievement_rate * 100, 2) : '0.00'
    }
    budgetChartRef.value.setOption(options);
  })
}

// 初始化获取图表数据
const initBudgetChartData = (getBudgetType) => {
  if (getBudgetType === "资金预算") {
    btnShowFlag.value = true;
    showInflowData();
  } else {
    btnShowFlag.value = false;
    btnTypeChange(1);
  }
};

// 在父组件中调用
// budgetType：1-资金预算；budgetType：2-经营预算
const initBudgetChart = (budgetType, yearVal) => {
  getYearVal.value = yearVal;
  // 基于准备好的dom，初始化echarts实例
  if (!budgetChartRef.value) {
    budgetChartRef.value = echarts.init(document.getElementById("budgetChart"));
  }
  initBudgetChartData(budgetType);
  return budgetChartRef.value
};
defineExpose({
  initBudgetChart,
});
</script>

<style lang="scss" scoped>
.budgetChartPage {
  width: 100%;
  height: 100%;
  position: relative;
  .btnGroupBox {
    position: absolute;
    z-index: 2;
    top: -10px;
    right: 10px;
    letter-spacing: 2px;
    .bigBtnBox {
      display: flex;
      justify-content: end;
      margin-bottom: 10px;
      .inflowBtn,
      .outflowBtn {
        width: 47px;
        height: 22px;
        line-height: 20px;
        color: #71a4da;
        text-align: center;
        background: url("@/assets/screenImg/commonImg/nomalBtn-Bg.png")
          no-repeat;
        background-size: 100% 100%;
        cursor: pointer;
      }
      .btnActive {
        font-family: SourceHanSansMedium;
        color: #ffda3a;
        background: url("@/assets/screenImg/commonImg/activeBtn-Bg.png")
          no-repeat;
        background-size: 100% 100%;
      }
    }
    .smBtnBox {
      display: flex;
      font-size: 12px;
      .smBtnItemStyle {
        width: 46px;
        height: 20px;
        line-height: 20px;
        margin-right: 10px;
        text-align: center;
        color: rgba(216, 240, 255, 0.5);
        text-shadow: 0px 0px 4px #0091ff;
        background: url("@/assets/screenImg/leaderImg/budget-smNomalBtn-Bg.png")
          no-repeat;
        background-size: 100% 100%;
        cursor: pointer;
      }
      .btnSmActive {
        color: #ffda3a;
        text-shadow: 0px 0px 10px #ffda3a, 0px 0px 4px #faff00;
        background: url("@/assets/screenImg/leaderImg/budget-smActiveBtn-Bg.png")
          no-repeat;
        background-size: 100% 100%;
      }
    }
  }
  .chartBox {
    width: 100%;
    height: 100%;
  }
}
</style>

<style lang="scss">
.screenChartToolTipBox {
  width: 120px;
  height: 63px;
  background: url("@/assets/screenImg/commonImg/chartToolTipBg.png") no-repeat;
  background-size: 100% 100%;
  color: #ffffff !important;
  text-shadow: 0px 2px 4px #000000;
  .tip-head {
    font-family: SourceHanSansMedium;
    margin-bottom: 7px;
  }
  .tip-cn {
    .cn-item {
      .item-cn {
        color: #ffda3a;
        font-family: SourceHanSansMedium;
        text-shadow: 0px 2px 4px #000000;
      }
    }
  }
}
</style>
